<template>
    <div class="ai-chat-container">
        <div class="chat-header">
            <h2>AI助手</h2>
            <div class="status-indicator" :class="{ active: isStreaming }"></div>
        </div>
        <div class="message-container" ref="messageContainer">
            <div v-for="(msg, index) in messages" :key="index" class="message" :class="msg.type">
                <div class="avatar">
                    <img v-if="msg.type === 'ai'" src="../../assets/logo.png" alt="AI助手头像">
                    <img v-else :src="getImageSrc(user.userface)" alt="用户头像">
                </div>
                <div class="content">
                    <div class="text" v-html="msg.text"></div>
                    <div class="time">{{ msg.time }}</div>
                </div>
            </div>
            <div v-if="isTyping" class="typing-indicator">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="input-area">
            <textarea v-model="userInput" placeholder="输入您的问题..." @keyup.enter="sendMessage"></textarea>

            <el-button type="primary" icon="el-icon-s-promotion" @click="sendMessage" :disabled="!userInput.trim()"></el-button>
           <!-- <button >
                <i class="fas fa-paper-plane"></i>
            </button>-->
        </div>
    </div>
</template>

<script>
    export default {

        name: "AiTalk",
        data() {
            return {
                user:JSON.parse(window.sessionStorage.getItem("user")),
                messages: [],
                userInput: '',
                isStreaming: false,
                isTyping: false,
                eventSource: null
            }
        },
        methods: {
            getImageSrc(headUrl){
                if(headUrl.startsWith('http')){
                    return headUrl;
                }
                return "http://47.95.17.160:81/"+headUrl;
            },
            async sendMessage() {
                if (!this.userInput.trim()) return;

                const userMsg = {
                    type: 'user',
                    text: this.userInput,
                    time: this.getCurrentTime()
                };
                this.messages.push(userMsg);

                this.isStreaming = true;
                this.isTyping = true;

                // 清空输入框
                const question = this.userInput;
                this.userInput = '';
                try {
                    let token = window.sessionStorage.getItem("token");
                    const response = await fetch(`/plateform/ai/talk/helloChatStream?input=${encodeURIComponent(question)}`, {
                        headers: {
                            'X-TOKEN':token,
                            'Content-Type': 'application/json;charset=UTF-8'
                        }
                    });

                    if (!response.ok) throw new Error('连接失败');

                    const reader = response.body.getReader();
                    const decoder = new TextDecoder('utf-8');

                    let aiResponse = {
                        type: 'ai',
                        text: '',
                        time: this.getCurrentTime()
                    };
                    this.messages.push(aiResponse);

                    const processStream = ({ done, value }) => {
                        if (done) {
                            this.isStreaming = false;
                            return;
                        }
                        const uint8Array = new Uint8Array(value);
                        let chunk = decoder.decode(uint8Array);
                        /*chunk = chunk.replace(' ','');
                        chunk = chunk.replace('data:','');*/
                        aiResponse.text += chunk;
                        aiResponse.text = aiResponse.text.trim();
                        aiResponse.text = aiResponse.text.replace('data:','');
                        this.$nextTick(() => {
                            this.scrollToBottom();
                        });

                        return reader.read().then(processStream);
                    };

                    reader.read().then(processStream);
                } catch (error) {
                    console.error('Error:', error);
                    this.isStreaming = false;
                    this.isTyping = false;
                }
            },
            getCurrentTime() {
                return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
            },
            scrollToBottom() {
                this.$nextTick(() => {
                    const container = this.$refs.messageContainer;
                    container.scrollTop = container.scrollHeight;
                });
            }
        }
    }
</script>

<style scoped>
    .ai-chat-container {
        display: flex;
        flex-direction: column;
        height: 100%;
        max-width: 800px;
        margin: 0 auto;
        background: #f5f7fa;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        overflow: hidden;
    }

    .chat-header {
        padding: 16px;
        background: #4a6fa5;
        color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .status-indicator {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background: #ccc;
    }

    .status-indicator.active {
        background: #4caf50;
        box-shadow: 0 0 8px #4caf50;
    }

    .message-container {
        flex: 1;
        padding: 16px;
        overflow-y: auto;
        background: #f5f7fa;
    }

    .message {
        display: flex;
        margin-bottom: 16px;
    }

    .message.user {
        justify-content: flex-end;
    }

    .avatar {
        width: 40px;
        height: 40px;
        margin-right: 12px;
    }

    .message.user .avatar {
        order: 1;
        margin-right: 0;
        margin-left: 12px;
    }

    .avatar img {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
    }

    .content {
        max-width: 70%;
    }

    .message.user .content {
        text-align: right;
    }

    .text {
        padding: 12px;
        border-radius: 18px;
        background: white;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        word-break: break-word;
    }

    .message.ai .text {
        background: #e3f2fd;
        border-top-left-radius: 4px;
    }

    .message.user .text {
        background: #4a6fa5;
        color: white;
        border-top-right-radius: 4px;
    }

    .time {
        font-size: 12px;
        color: #777;
        margin-top: 4px;
    }

    .input-area {
        display: flex;
        padding: 16px;
        background: white;
        border-top: 1px solid #eee;
    }

    textarea {
        flex: 1;
        padding: 12px;
        border: 1px solid #ddd;
        border-radius: 24px;
        resize: none;
        outline: none;
        font-family: inherit;
        transition: border 0.3s;
    }

    textarea:focus {
        border-color: #4a6fa5;
    }

    button {
        width: 48px;
        height: 48px;
        margin-left: 12px;
        border: none;
        border-radius: 50%;
        background: #4a6fa5;
        color: white;
        cursor: pointer;
        transition: background 0.3s;
    }

    button:disabled {
        background: #ccc;
        cursor: not-allowed;
    }

    button:hover:not(:disabled) {
        background: #3a5a80;
    }

    .typing-indicator {
        display: flex;
        padding: 12px;
        background: #e3f2fd;
        border-radius: 18px;
        width: fit-content;
        margin-bottom: 16px;
    }

    .typing-indicator span {
        width: 8px;
        height: 8px;
        margin: 0 2px;
        background: #4a6fa5;
        border-radius: 50%;
        opacity: 0.4;
        animation: typing 1s infinite;
    }

    .typing-indicator span:nth-child(2) {
        animation-delay: 0.2s;
    }

    .typing-indicator span:nth-child(3) {
        animation-delay: 0.4s;
    }

    @keyframes typing {
        0%, 100% {
            opacity: 0.4;
            transform: translateY(0);
        }
        50% {
            opacity: 1;
            transform: translateY(-4px);
        }
    }
</style>
